/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.compomics.proteomusicplayer.MS1;

import com.compomics.util.experiment.massspectrometry.Spectrum;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.List;
import org.apache.commons.math.MathException;
import org.apache.commons.math.transform.FastSineTransformer;

/**
 *
 * @author Kenneth
 */
public class SpectrumToSineTransformer {

    public static byte[] getSineFromSpectrum(Spectrum aSpectrum) throws MathException, IOException {
        double[] convertSpectrumToSine = convertSpectrumToFrequencyArray(aSpectrum);
        return getSine(convertSpectrumToSine);
    }

    private static double[] convertSpectrumToFrequencyArray(Spectrum aSpectrum) throws MathException, IOException {
        double[] mzValues = aSpectrum.getMzValuesAsArray();
        double[] intensities = aSpectrum.getIntensityValuesAsArray();
        double[] sineArray = new double[mzValues.length];
        sineArray[0] = 0;
        for (int i = 1; i < sineArray.length; i++) {
            sineArray[i] = mzValues[i] * intensities[i];
        }
        return sineArray;
    }

    private static byte[] getSine(double[] spectrumAsSignal) throws MathException, IOException {
        if (spectrumAsSignal.length > 0) {
            int padding = 0;
            //padding is required to get a power of 2 in sample size !
            int sampleSize = spectrumAsSignal.length;
            int paddedSampleSize = 8;
            while (sampleSize > paddedSampleSize) {
                paddedSampleSize = paddedSampleSize * 2;
            }
            padding = paddedSampleSize - sampleSize;
            if (padding != 0) {
                double[] temp = new double[spectrumAsSignal.length + padding];
                System.arraycopy(spectrumAsSignal, 0, temp, 0, spectrumAsSignal.length);
                spectrumAsSignal = temp;
            }
            FastSineTransformer transformer = new FastSineTransformer();
            double[] inversetransform = transformer.inversetransform(spectrumAsSignal);
            return convertSineToByteArray(inversetransform);
        }
        return null;
    }

    private static byte[] convertSineToByteArray(double[] sineWave) throws IOException {
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        DataOutputStream dataStream = new DataOutputStream(byteStream);
// write each element of your double[] to dataStream
        for (double aSineElement : sineWave) {
            dataStream.writeDouble(aSineElement);
            dataStream.flush();
        }
        dataStream.flush();
        dataStream.close();
        byteStream.close();
        return byteStream.toByteArray();
    }

}
